<?php
/**
*
* @package phpBB3
* @version $Id$
* @copyright (c) 2010
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/	
    	
/*
*	This service will:
*	1. If it's in trading time, check all delegations and get related stock price/volume 
*		to see if the delegations can be done.
*	2. If it's not in trading time, get stock price/volume for all corp for each trading day. 
* 
*	Note: this file should be in ASCII format!
*/	
 
define('IN_PHPBB', true);
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include_once($phpbb_root_path . 'common.' . $phpEx);
include_once($phpbb_root_path . 'sv_common.' . $phpEx);

// allow the service to run up to 15 minutes as it may take long time to grab data from TWSE and OTC.
if (!get_cfg_var('safe_mode')) 
{
	set_time_limit(900);	
} 

// check the service lock.
$a = new service_lock(basename(__FILE__));
if ($a->lock() == false)
{
	// another instance is running.
	echo "\n\nanother instance is running.\n";
	echo date('Y/m/d H:i:s', get_taiwan_time()) . PHP_EOL . PHP_EOL;
	die;	
}

// get taiwan time.		
$time = get_taiwan_time();

// print service log.
print_service_log(__FILE__);

		
if (is_trading_time($time) && is_trading_day($time))
{		
	echo "In trading time\n";
				
	// deal with all transactions.	
	begin_service_task('deal_all_transaction');
	deal_all_transaction();
	end_service_task('deal_all_transaction');
}
else if (is_trading_day($time))
{
	echo "trading day, not in trading time\n";
	// handle Off-hour Trading after trading time 1:30 PM, and we only do this once for each trading day. 	
	if (service_task_completed_for_latest_trading_date('handle_off_hour_trading') == false)
	{
		begin_service_task('handle_off_hour_trading');
		deal_all_transaction(true);
		end_service_task('handle_off_hour_trading');
	}	
	
	// clear unfinished transactions after the end of a trading day.
	if (service_task_completed_for_latest_trading_date('clear_transaction') == false)
	{
		begin_service_task('clear_transaction');
		clear_transaction();
		end_service_task('clear_transaction');
	}
	
	// update stock price/volume info right after trading time. 
	if (service_task_completed_for_latest_trading_date('update_all_stock_price') == false)
	{
		// get all the stock price/volume info of the latest finished trading day
		begin_service_task('update_all_stock_price');
		update_all_stock_price();
		end_service_task('update_all_stock_price');
	}
}
else
{
	echo "Not trading day and time\n";
	
	
}

// print service log end.
print_service_log_end();

?>